; Copyright (c) 2008, John Cronin
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
;     * Redistributions of source code must retain the above copyright
;       notice, this list of conditions and the following disclaimer.
;     * Redistributions in binary form must reproduce the above copyright
;       notice, this list of conditions and the following disclaimer in the
;       documentation and/or other materials provided with the distribution.
;     * Neither the name of the copyright holder nor the
;       names of its contributors may be used to endorse or promote products
;       derived from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY
; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
; DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

; Code to go to 64 bit execution

; enable pae (set cr4.pae to 1)
; load cr3 with pml4t
; set ia32_efer.lme to 1 (need to use rdmsr/wrmsr)
; set cr0.pg to 1
; load a 64-bit gdt with cs.l = 1 and cs.d = 0

global go64

extern kif

IA32_EFER		EQU	0xc0000080
LME			EQU 	0x100


;void go64(unsigned long int pml4t, unsigned long long int e_point)
go64:
	push			ebp
	mov			ebp, esp
	
	mov			eax, cr4
	or			eax, 0x20
	mov			cr4, eax
	
	mov			eax, [ebp + 8]
	mov			cr3, eax
	
	mov			ecx, IA32_EFER
	rdmsr
	or			eax, LME
	wrmsr
	
	mov			eax, cr0
	or			eax, 0x80000000
	and			eax, 0x9fffffff
	mov			cr0, eax
	
; use our own gdt
	lgdt			[gdt64info]
	jmp			0x8:.owngdt
	
.owngdt:
[BITS 64]	
	mov			rax, [rbp + 12]
	xor			rdx, rdx
	mov			edx, [kif]
	push			rdx
	xchg			bx, bx
	
	call			rax
	add			rsp, 8
	xchg			bx, bx
	jmp			$	

[BITS 32]

section .data
align 32
gdt64info:
        dw 			gdt64_end - gdt64 - 1
        dd 			gdt64		; linear address	
	
	
	
section .gdt
align 32
gdt64   dd      0,0     ; null
code    db      0xff, 0xff, 0x00, 0x00, 0x00, 10011010b, 10101111b, 0x00
data    db      0xff, 0xff, 0x00, 0x00, 0x00, 10010010b, 11001111b, 0x00
code3	db	0xff, 0xff, 0x00, 0x00, 0x00, 11111110b, 10101111b, 0x00
data3	db	0xff, 0xff, 0x00, 0x00, 0x00, 11110010b, 11001111b, 0x00
tss_ent	dd	0, 0
.end

times (2048 - .end + gdt64) db 0
gdt64_end:

